﻿#region 命名空间

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using WinnerCMS.Common;
using System.IO;

#endregion

namespace WinnerCMS.BLL.PageFactory
{
    public static class UrlMap
    {
        private static Dictionary<string, string> _urls;


        public static void Add(string key, string url)
        {
            lock (typeof (UrlMap))
            {
                if (_urls == null)
                {
                    _urls = new Dictionary<string, string>();
                    _urls.Add(key, url);
                }
                else
                {
                    if (_urls.ContainsKey(key) == false)
                        _urls.Add(key, url);
                }
            }
        }

        public static void Remove(string ID)
        {
            lock (typeof (UrlMap))
            {
                _urls.Remove(ID);
            }
        }

        public static bool TryGet(string ID, out string value)
        {
            //如果内存里面没有，则考虑从缓存文件里面读取
            if (_urls == null)
            {
                FileInfo fi = new FileInfo(HttpServer.MapPath("~/Config/WinnerCMS.UrlMap.config"));
                if (MyDateTime.DateDiff(DateDiffOption.Day, fi.CreationTime, DateTime.Now) > 1)
                {
                    value = null;
                    return false;
                }
                _urls = SerializableHelper.DeSerialize<string, string>(fi);
            }
            if (_urls == null) //如果还没有，就返回不存在
            {
                value = null;
                return false;
            }
            return _urls.TryGetValue(ID, out value);
        }

        /// <summary>
        /// 保存到缓存文件
        /// </summary>
        public static void Save()
        {
            lock (typeof (UrlMap))
            {
                SerializableHelper.Serialize(_urls, HttpServer.MapPath("~/Config/WinnerCMS.UrlMap.config"));
            }
        }
    }
}